import { buildCartProductKey, ICartProduct, IProductWithSelected, IResult } from "models";

export class CartLocalStorage {
    public static loadProducts(): IResult<ICartProduct[]> {
        try {
            const json = localStorage.getItem(`CartProducts`);
            if (!json) return { success: true, data: [] };
            const list: ICartProduct[] = JSON.parse(json);
            //读取或解析失败,也直接用空数组
            if (!list.find) return { success: true, data: [] };
            return { success: true, data: list };
        } catch (err: any) {
            return { success: false, code: 500, error: err?.message || err };
        }
    }
    public static saveProducts(list: ICartProduct[]): IResult<null> {
        try {
            localStorage.setItem(`CartProducts`, JSON.stringify(list));
            return { success: true, data: null };
        } catch (err: any) {
            return { success: false, code: 500, error: err?.message || err };
        }
    }
    public static clearProducts(): void {
        CartLocalStorage.saveProducts([]);
    }
    public static addProduct(product: IProductWithSelected) {
        let listRet = CartLocalStorage.loadProducts();
        if (!listRet.success) {
            console.error('购物车加载本地数据失败', listRet, '将使用全空购物车开始');
        }

        let cKey = buildCartProductKey(product);
        let list = listRet.success ? listRet.data : [];
        let cp = list.find(p => p.key === cKey);
        if (cp) {
            cp.quantity += 1;
        }
        else {
            cp = {
                ...product,
                key: cKey,
                quantity: 1,
            };
            list.push(cp);
        }
        CartLocalStorage.saveProducts(list);
    }
}